package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.query.StrategyCommentQuery;
import cn.wolfcode.luowowo.comment.repository.StrategyCommentServiceRepository;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import cn.wolfcode.luowowo.exception.LogicException;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {

    @Autowired
    private MongoTemplate template;

    @Autowired
    private StrategyCommentServiceRepository repository;

    @Override
    public void save(StrategyComment detail, UserInfo userInfo) {
        if (detail == null || userInfo == null) {
            throw new LogicException("参数错误");
        }
        detail.setHeadUrl(userInfo.getHeadImgUrl());
        detail.setCity(userInfo.getCity());
        detail.setUsername(userInfo.getNickname());
        detail.setUserId(userInfo.getId());
        detail.setLevel(userInfo.getLevel());
        detail.setCreateTime(new Date());
        // 插入数据到mongodb中
        repository.save(detail);
    }

    @Override
    public int countByStrategyId(Long id) {
        Aggregation aggregation = Aggregation.newAggregation(Aggregation.match(Criteria.where("detailId").is(id)),
                Aggregation.group("detailId").count().as("count"));
        AggregationResults<Map> aggregate = template.aggregate(aggregation, "strategy_comment", Map.class);
        return (int) aggregate.getMappedResults().get(0).get("count");
    }

    @Override
    public Page<StrategyComment> query(StrategyCommentQuery qo) {
        // 根据攻略Id 查询 评论总数
        Query query = new Query();
        if (qo.getDetailId() != null) {
            query.addCriteria(Criteria.where("detailId").is(qo.getDetailId()));
        }
        long count = template.count(query, StrategyComment.class);
        // 如果 结果总数为 0 就不需要在查询 评论
        if (count == 0) {
            return Page.empty();
        }
        // 分页查询 评论
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.DESC, "createTime");
        query.with(pageable);
        List<StrategyComment> strategyComments = template.find(query, StrategyComment.class);
        return new PageImpl<>(strategyComments, pageable, count);
    }

    @Override
    public void commentThumbUp(String toid, Long fromid) {
        if (!StringUtils.hasLength(toid) || fromid == null || fromid <= 0) {
            throw new LogicException("参数错误");
        }
        // 1: 查询出游记, 判断当前用户有没有点赞
        Optional<StrategyComment> opt = repository.findById(toid);
        StrategyComment comment = opt.get();
        if (comment == null) {
            return;
        }
        List<Long> list = comment.getThumbuplist();
        if (list.contains(fromid)) {
            // 如果已经点赞, 那么就取消点赞
            comment.setThumbupnum(comment.getThumbupnum() - 1);
            list.remove(fromid);
        } else {
            // 如果没有点赞, 那么就添加点赞数, 并且将用户的编号, 加入评论点赞列表
            comment.setThumbupnum(comment.getThumbupnum() + 1);
            list.add(fromid);
        }
        repository.save(comment);
    }
}
